<?php

namespace plugin\voice\app\modelHandler;


use plugin\voice\app\model\Apikey;
use plugin\voice\app\service\ChatGpt;
use Throwable;
use Webman\Medoo\Medoo as db;

class GptAudio extends Gpt3
{
    protected $isUserApikey = false;

    protected $path = '/v1/audio/speech';

    public function __construct($request = null)
    {
        $settings  = db::get('voice_settings','*');
        $this->api = $settings['gpt3_api_host'];
        if ($request && $authorization = $request->header('Authorization')) {
            $this->apikey = explode(' ', $authorization)[1] ?? '';
            $this->isUserApikey = true;
        }
    }

    public function buildData($data)
    {
        $settings  = db::get('voice_settings','*');
        [$model, $input, $voice] = $data;
        $path = $this->path;
        [$schema, $host] = $this->getApi();
        $apiKey = $settings['gpt3_api_key'];
        $data = array(
            'model' => $model,
            'input' => $input,
            'voice' => $voice,
        );
        $body = json_encode($data);
        $bodyLength = strlen($body);
        return "POST $path HTTP/1.1\r\n" .
            "Host: $host\r\n" .
            "Connection: close\r\n" .
            "Content-Type: application/json\r\n" .
            "Authorization: Bearer $apiKey\r\n" .
            "Accept: */*\r\n" .
            "Content-Length: $bodyLength\r\n\r\n" .
            $body;
    }

}